<template>
  <el-card style="width: 100%">
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input
          :placeholder="$t('table.placeholder')"
          clearable
          v-model="queryForm.search"
        ></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetList">
        {{ $t("table.search") }}
      </el-button>
      <el-button type="primary" @click="handlerDialogValue()">
        添加分类
      </el-button>
    </el-row>

    <!-- 分类列表 -->
    <el-table
      :data="tableData"
      border
      class="listTable"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :expand-row-keys="expandedKeys"
    >
      <!-- 动态生成表格列 -->
      <el-table-column
        v-for="option in options"
        :key="option.prop"
        :prop="option.prop"
        :label="option.label"
        :width="option.width"
      >
        <template #default="scope" v-if="option.prop === 'icon'">
          <el-image
            :src="scope.row.icon"
            :alt="scope.row.name"
            fit="cover"
            :style="{ width: '50px', height: '50px' }"
          />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column :label="$t('common.actions')" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handlerDialogValue(row)">
              <el-icon><View /></el-icon>
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handlerDialogValue(row)"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteCategoryHandler(row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 弹窗组件 -->
  <Dialog
    v-model:modelValue="dialogVisible"
    :dialogTitle="dialogTitle"
    v-if="dialogVisible"
    @initGetList="initGetList"
    :dialogTableValue="dialogTableValue"
  />
</template>

<script setup>
import { ref } from "vue";
import { Delete, Edit, Search, View } from "@element-plus/icons-vue";
import { getCategories, deleteCategory } from "@/api/category";
import { ElMessage, ElMessageBox } from "element-plus";
import { options } from "./options";
import { useI18n } from "vue-i18n";
import Dialog from "./components/dialog.vue";
import { isNull } from "@/utils/filters";
import { formatTreeData } from "@/utils/public";

const i18n = useI18n();

// 查询表单
const queryForm = ref({
  search: "",
});

// 表格数据
const tableData = ref([]);
const total = ref(0);

// 在 script setup 中添加 expandedKeys ref
const expandedKeys = ref([]);

// 获取分类列表
const initGetList = async () => {
  try {
    const res = await getCategories();
    console.log("res", res);
    // 添加空值检查
    if (res.data && res.data.data) {
      // 将扁平数据转换为树形结构
      tableData.value = formatTreeData(res.data.data, "id", "parentId");
      // 设置第一层节点的展开
      expandedKeys.value = tableData.value.map((item) => item.id);
    } else {
      tableData.value = [];
      expandedKeys.value = [];
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
    tableData.value = [];
    expandedKeys.value = [];
  }
};

// 初始化加载
initGetList();

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogTableValue = ref({});

// 处理弹窗显示
const handlerDialogValue = (row) => {
  if (isNull(row)) {
    dialogTitle.value = "添加分类";
    dialogTableValue.value = {};
  } else {
    dialogTitle.value = "编辑分类";
    dialogTableValue.value = JSON.parse(JSON.stringify(row));
  }
  dialogVisible.value = true;
};

// 删除分类
const deleteCategoryHandler = (row) => {
  ElMessageBox.confirm(
    i18n.t("dialog.deleteConfirm"),
    i18n.t("dialog.warning"),
    {
      confirmButtonText: i18n.t("common.confirm"),
      cancelButtonText: i18n.t("common.cancel"),
      type: "warning",
    }
  )
    .then(async () => {
      await deleteCategory(row.id);
      ElMessage({
        type: "success",
        message: i18n.t("dialog.deleteSuccess"),
      });
      initGetList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: i18n.t("dialog.deleteCanceled"),
      });
    });
};
</script>

<style src="@/css/list.css"></style>
